package com.spica.platform.feign.config;

import com.spica.platform.common.constant.CommonConstant;
import com.spica.platform.common.constant.SecurityConstant;
import feign.RequestInterceptor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import reactivefeign.client.ReactiveHttpRequest;
import reactivefeign.client.ReactiveHttpRequestInterceptor;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * feign拦截器，只包含基础数据
 */
public class FeignReactiveInterceptorConfig {
    /**
     * 使用feign client访问别的微服务时，将上游传过来的client等信息放入header传递给下一个服务
     */
	@ConditionalOnMissingBean(RequestInterceptor.class)
    @Bean
    public ReactiveHttpRequestInterceptor  baseFeignInterceptor() {
        return  new ReactiveHttpRequestInterceptor () {
			@Override
			public Mono<ReactiveHttpRequest> apply(ReactiveHttpRequest request) {
				List<String> tenants = request.headers().get(CommonConstant.TENANT_ID_PARAM);
				if (CollectionUtils.isNotEmpty(tenants)) {
	                request.headers().put(SecurityConstant.TENANT_HEADER,tenants);
	            }
				return Mono.just(request);
			}
        };
    }
}
